package com.codechuan.hallo_web.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.codechuan.hallo_web.entity.*;
import com.codechuan.hallo_web.mapper.*;
import com.codechuan.hallo_web.service.JtApiService;
import com.codechuan.hallo_web.utils.EncryptionUtil;
import com.codechuan.hallo_web.utils.RedisUtils;
import com.codechuan.hallo_web.utils.ResultUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

@Service
public class JtApiServiceImpl implements JtApiService {

    @Resource
    private SysKeyNzMapper sysKeyNzMapper;

    @Resource
    private SysUserAccountNzMapper sysUserAccountNzMapper;

    @Resource
    private SysUserConfigNzMapper sysUserConfigNzMapper;

    @Resource
    private SysAppUpdateMapper sysAppUpdateMapper;

    @Resource
    private SysUserAccountNzTwoMapper sysUserAccountNzTwoMapper;

    @Resource
    private SysCityMapper sysCityMapper;

    @Resource
    private SysUserOrderNzMapper sysUserOrderNzMapper;
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * @param hashMap 传过来的数据
     * @return 返回加密数据
     * @Deprecated 鸡腿登陆接口
     */
    @Override
    public String login(HashMap<String, String> hashMap) {
        try {
            String account = hashMap.get("account");
            String key = hashMap.get("key");
            SysKeyNz sysKeyNz = sysKeyNzMapper.selectKey(key);
            if (sysKeyNz == null) {
                return EncryptionUtil.encrypt(ResultUtils.success(null, "卡密错误~", 500));
            }
            // 判断卡密是否封禁
            if (sysKeyNz.getStatus().equals("1"))
                return EncryptionUtil.encrypt(ResultUtils.success(null, "卡密被封禁~", 500));

            // 判断卡密是否非本人使用
            if (sysKeyNz.getPersonName() != null && !sysKeyNz.getPersonName().equals(account))
                return EncryptionUtil.encrypt(ResultUtils.success(null, "请勿使用他人卡密~", 500));
            // 校验卡密是否到期
            Date expirationTime = sysKeyNz.getExpirationTime();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            if (expirationTime == null) {
                String keySubstring = sysKeyNz.getKeyNumber().substring(0, 4);
                Calendar calendar = Calendar.getInstance();
                switch (keySubstring) {
                    case "JTTK":
                        calendar.add(Calendar.DAY_OF_MONTH, 1);
                        sysKeyNz.setExpirationTime(calendar.getTime());
                        break;
                    case "JTZK":
                        calendar.add(Calendar.DAY_OF_MONTH, 7);
                        sysKeyNz.setExpirationTime(calendar.getTime());
                        break;
                    case "JTYK":
                        calendar.add(Calendar.DAY_OF_MONTH, 32);
                        sysKeyNz.setExpirationTime(calendar.getTime());
                        break;
                    case "JTCS":
                        calendar.add(Calendar.HOUR_OF_DAY, 5);
                        sysKeyNz.setExpirationTime(calendar.getTime());
                        break;
                }
                // 第一次使用卡密设置卡密到期时间,和使用者
                sysKeyNz.setPersonName(account);
                // 设置激活时间
                sysKeyNz.setActivationTime(new Date());
                // 设置已激活
                sysKeyNz.setIsActivated("1");
                // 修改卡密信息
                sysKeyNzMapper.updateByPrimaryKey(sysKeyNz);
            } else {
                // 判断用户是否为空 为空就是被解绑了重新赋值
                if (sysKeyNz.getPersonName() == null) {
                    sysKeyNz.setPersonName(account);
                    sysKeyNzMapper.updateByPrimaryKey(sysKeyNz);
                }

                // 校验用户是否到期
                String ddTime = simpleDateFormat.format(sysKeyNz.getExpirationTime());
                String sysTime = simpleDateFormat.format(new Date());
                LocalDateTime dateTimeA = LocalDateTime.parse(ddTime, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
                LocalDateTime dateTimeB = LocalDateTime.parse(sysTime, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
                if (dateTimeA.isBefore(dateTimeB)) {
                    return EncryptionUtil.encrypt(ResultUtils.success(null, "卡密已到期~", 500));
                }

            }
            // 判断用户是否存在
            SysUserAccountNz sysUserAccountNz = sysUserAccountNzMapper.selectOnAccount(account);
            // 判断用户是否封禁
            if (sysUserAccountNz != null && sysUserAccountNz.getAccountStatus().equals("1")) {
                return EncryptionUtil.encrypt(ResultUtils.success(null, "您已被封禁~", 500));
            }
            if (sysUserAccountNz == null) {
                // 保存用户到数据库
                SysUserAccountNz sysUserAccountNz1 = new SysUserAccountNz();
                sysUserAccountNz1.setAccount(account);
                sysUserAccountNz1.setAccountStatus("0");
                sysUserAccountNzMapper.insert(sysUserAccountNz1);
            }
            // 获取最新版本
            SysAppUpdate sysAppUpdate = sysAppUpdateMapper.selectByPrimaryKey("鸡腿");

            Boolean b = stringRedisTemplate.opsForValue().getOperations().hasKey("LOGIN_JT_" + account);
            if (b == false) {
                RedisUtils.incrementKeyWithExpireTime(stringRedisTemplate, "LOGIN_JT_" + account);
            }
            return EncryptionUtil.encrypt(ResultUtils.success(sysAppUpdate.getVersion(), "登录成功", 200));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * @param hashMap 参数
     * @return 返回配置文件实体类
     * @Deprecated 读取鸡腿用户卡密配置
     */
    @Override
    public String getJtUserConfig(HashMap<String, String> hashMap) {
        ArrayList<SysUserConfigNz> sysUserConfigNz = sysUserConfigNzMapper.selectList(hashMap.get("account"));
        if (!sysUserConfigNz.isEmpty()) {
            try {
                return EncryptionUtil.encrypt(ResultUtils.success(JSONObject.toJSONString(sysUserConfigNz.get(0)), "success", 200));

            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        } else {
            try {
                return EncryptionUtil.encrypt(ResultUtils.success("null", "success", 200));
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }

    /**
     * @param hashMap 参数
     * @return 返回到期时间
     * @Deprecated 获取用户到期时间
     */
    @Override
    public String selectUserExitTime(HashMap<String, String> hashMap) {
        String exitTime = sysKeyNzMapper.selectUserExitTime(hashMap.get("key"));
        try {
            return EncryptionUtil.encrypt(ResultUtils.success(exitTime, "success", 200));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * @param hashMap phone 手机号
     * @return 返回主号信息
     * @Deprecated 获取用户主号token信息
     */
    @Override
    public String getUserAccount(HashMap<String, String> hashMap) {
        SysUserAccountNzTwo user = sysUserAccountNzTwoMapper.selectByPrimaryAccount(hashMap.get("account"));
        try {
            return EncryptionUtil.encrypt(ResultUtils.success(JSONObject.toJSONString(user), "success", 200));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * @param hashMap 用户账号
     * @Deprecated 修改用户表中的token和ticket
     */
    @Override
    public String updateAccountToken(HashMap<String, String> hashMap) {
        String account = hashMap.get("account");
        String token = hashMap.get("token");
        String ticket = hashMap.get("ticket");
        int i = sysUserAccountNzTwoMapper.updateAccountToken(account, token, ticket);
        try {
            String result = "1";
            if (i <= 0) {
                result = "0";
            }
            return EncryptionUtil.encrypt(ResultUtils.success(result, "success", 200));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * @param hashMap 城市
     * @Deprecated 获取指定城市编码
     */
    @Override
    public String selectZdCsCityCode(HashMap<String, String> hashMap) {
        StringBuilder stringBuilder = new StringBuilder();
        String cityName = hashMap.get("cityName");
        if (cityName.contains(",")) {
            String[] split = cityName.split(",");
            for (String name : split) {
                String cityCode = sysCityMapper.selectCodeByCityName(name);
                stringBuilder.append(cityCode).append(",");
            }
        } else {
            String cityCode = sysCityMapper.selectCodeByCityName(cityName);
            stringBuilder.append(cityCode);
        }

        try {
            return EncryptionUtil.encrypt(ResultUtils.success(stringBuilder.toString(), "success", 200));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * @param hashMap 数据
     * @Deprecated 修改主号状态
     */
    @Override
    public String updateAccountTokenStatus(HashMap<String, String> hashMap) {
        String account = hashMap.get("account");
        sysUserAccountNzTwoMapper.updateAccountTokenStatus(account);
        try {
            return EncryptionUtil.encrypt(ResultUtils.success(null, "success", 200));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * @param hashMap 数据
     * @Deprecated 保存用户配置文件
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String saveAccountConfig(HashMap<String, String> hashMap) {
        String data = hashMap.get("data");
        JSONObject jsonData = JSONObject.parseObject(data);
        SysUserConfigNz sysUserConfigNz = new SysUserConfigNz();
        sysUserConfigNz.setJdMs(jsonData.getString("jdMs"));
        sysUserConfigNz.setPxGz(jsonData.getString("pxGz"));

        sysUserConfigNz.setRzMs(jsonData.getString("rzMs"));
        sysUserConfigNz.setZjDx(jsonData.getString("zjDx"));
        sysUserConfigNz.setYdGs(jsonData.getString("ydGs"));

        sysUserConfigNz.setQdDw(jsonData.getString("qdDw"));
        sysUserConfigNz.setMiniMoney(jsonData.getString("miniMoney"));
        sysUserConfigNz.setMaxMoney(jsonData.getString("maxMoney"));
        sysUserConfigNz.setDtStartDes(jsonData.getString("dtStartDes"));
        sysUserConfigNz.setDtEndDes(jsonData.getString("dtEndDes"));
        sysUserConfigNz.setXcZdJl(jsonData.getString("xcZdJl"));
        sysUserConfigNz.setSld(jsonData.getString("sld"));
        sysUserConfigNz.setPcGzCheck(jsonData.getString("pcGzCheck"));
        sysUserConfigNz.setPcMinPerson(jsonData.getString("pcMinPerson"));
        sysUserConfigNz.setPcMaxPerson(jsonData.getString("pcMaxPerson"));
        sysUserConfigNz.setDxGzCheck(jsonData.getString("dxGzCheck"));
        sysUserConfigNz.setDxMinPerson(jsonData.getString("dxMinPerson"));
        sysUserConfigNz.setDxMaxPerson(jsonData.getString("dxMaxPerson"));
        sysUserConfigNz.setSsGzCheck(jsonData.getString("ssGzCheck"));
        sysUserConfigNz.setSsMinPerson(jsonData.getString("ssMinPerson"));
        sysUserConfigNz.setSsMaxPerson(jsonData.getString("sMaxPerson"));
        sysUserConfigNz.setPcCsCheck(jsonData.getString("pcCsCheck"));
        sysUserConfigNz.setPcCsText(jsonData.getString("pcCsText"));
        sysUserConfigNz.setZdCsCheck(jsonData.getString("zdCsCheck"));
        sysUserConfigNz.setZdCsText(jsonData.getString("zdCsText"));
        sysUserConfigNz.setLxQd(jsonData.getString("lxQd"));
        sysUserConfigNz.setAccount(jsonData.getString("account"));
        // 先删除配置
        sysUserConfigNzMapper.deleteByPrimaryKey(jsonData.getString("account"));
        int i = sysUserConfigNzMapper.insert(sysUserConfigNz);
        try {
            String result = "1";
            if (i <= 0) {
                result = "0";
            }
            return EncryptionUtil.encrypt(ResultUtils.success(result, "success", 200));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * @param hashMap 账号
     * @Deprecated 获取用户订单集合
     */
    @Override
    public String getUserOrderList(HashMap<String, String> hashMap) {
        List<SysUserOrderNz> orderNzs = sysUserOrderNzMapper.selectListOrder(hashMap.get("account"));
        try {
            HashMap<String, Object> hashMap1 = new HashMap<>();
            hashMap1.put("orderList", JSONObject.toJSONString(orderNzs));
            return EncryptionUtil.encrypt(ResultUtils.success(JSONObject.toJSONString(hashMap1), "success", 200));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * @param hashMap 账号
     * @Deprecated 删除所有用户订单
     */
    @Override
    public String deleteOrderInfo(HashMap<String, String> hashMap) {
        int i = sysUserOrderNzMapper.deleteAllOrder(hashMap.get("account"));
        try {
            String result = "1";
            if (i <= 0) {
                result = "0";
            }
            return EncryptionUtil.encrypt(ResultUtils.success(result, "success", 200));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * @param hashMap 数据
     * @Deprecated 新增用户订单
     */
    @Override
    public String addUserOrder(HashMap<String, String> hashMap) {
        String data = hashMap.get("data");
        JSONObject jsonObject = JSONObject.parseObject(data);

        SysUserOrderNz sysUserOrderNz = new SysUserOrderNz();
        sysUserOrderNz.setDriverjourneyguid(jsonObject.getString("driverJourneyGuid"));
        sysUserOrderNz.setPaxjourneyguid(jsonObject.getString("paxJourneyGuid"));
        sysUserOrderNz.setPrice(jsonObject.getString("price"));
        sysUserOrderNz.setPersonnumber(jsonObject.getString("personNumber"));
        sysUserOrderNz.setOrderdes(jsonObject.getString("orderDes"));
        sysUserOrderNz.setCarpooltext(jsonObject.getString("carPoolText"));
        sysUserOrderNz.setCreatetime(new Date());
        sysUserOrderNz.setAccount(jsonObject.getString("account"));
        sysUserOrderNz.setMsg(jsonObject.getString("msg"));
        sysUserOrderNz.setStartaddress(jsonObject.getString("startAddress"));
        sysUserOrderNz.setEndaddress(jsonObject.getString("endAddress"));
        sysUserOrderNz.setPassengername(jsonObject.getString("passengerName"));
        sysUserOrderNz.setOrdertype(jsonObject.getString("orderType"));
        sysUserOrderNzMapper.insert(sysUserOrderNz);
        try {
            return EncryptionUtil.encrypt(ResultUtils.success(null, "success", 200));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * @param hashMap 数据
     * @Deprecated 鸡腿解绑
     */
    @Override
    public String jtNoBind(HashMap<String, String> hashMap) {
        String keyNumber = hashMap.get("keyNumber");
        // 通过BL + 账号获取次数
        Boolean b = stringRedisTemplate.opsForValue().getOperations().hasKey("JT_" + keyNumber);
        if (b) {
            // 获取解绑次数
            String noBindNumber = stringRedisTemplate.opsForValue().get("JT_" + keyNumber);
            Integer i = Integer.valueOf(noBindNumber);
            if (i > 5) {
                try {
                    return EncryptionUtil.encrypt(ResultUtils.success("1", "本周解绑次数已满!", 500));
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            } else {
                try {
                    RedisUtils.incrementKeyWithExpireTime(stringRedisTemplate, "JT_" + keyNumber);
                    // 解绑账号机器吗
                    sysKeyNzMapper.noBind(keyNumber);
                    return EncryptionUtil.encrypt(ResultUtils.success("1", "解绑成功,请重新登陆~", 200));
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        } else {
            try {
                RedisUtils.incrementKeyWithExpireTime(stringRedisTemplate, "JT_" + keyNumber);
                // 解绑账号机器吗
                sysKeyNzMapper.noBind(keyNumber);
                return EncryptionUtil.encrypt(ResultUtils.success("1", "解绑成功,请重新登陆~", 200));
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }
}
